<template>
  <div>
    <h1>门票购买页</h1>
    <el-table :data="ticket">
      <el-table-column label="门票名称" prop="scenicTicketName"></el-table-column>
      <el-table-column label="门票价格" prop="scenicTicketPrice"></el-table-column>
      <el-table-column label="发布时间">
        <template #default="scope">
          {{scope.row.scenicTicketPublishtime.substring(0,10)}}
        </template>
      </el-table-column>
      <el-table-column label="开始时间">
        <template #default="scope">
          {{scope.row.scenicTicketStart.substring(0,10)}}
        </template>
      </el-table-column>
      <el-table-column label="截止时间">
        <template #default="scope">
          {{scope.row.scenicTicketExpire==null ? '长期有效' : scope.row.scenicTicketExpire.substring(0,10)}}
        </template>
      </el-table-column>
      <el-table-column label="门票状态">
        <template #default="scope">
          <div v-if="scope.row.scenicTicketStatus==='UnExpire'">
            <el-tag type="success">{{ticketType.UnExpire}}</el-tag>
          </div>
          <div v-else>
            <el-tag>{{ticketType.Expire}}</el-tag>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-divider/>
    <el-steps align-center :active="active" process-status="success" finish-status="success" >
      <el-step :status="status1"  title="填写订单信息"></el-step>
      <el-step :status="status2"  title="支付订单"></el-step>
      <el-step  title="订购完成"></el-step>
    </el-steps>
    <el-divider/>
<!--    填写订单信息-->
    <div v-if="active===0">
      <h1>填写订单信息</h1>
      <p style="color: crimson;">目前仅支持系统在册用户购买，未注册用户请先注册方可正常购买，入园时间请选择7:00-19:00时间段内的时间。</p>
      <el-row justify="center">
        <el-form :model="form" ref="orderForm" label-width="120px" :rules="rules">
          <el-form-item label="选择入园时间" prop="ticketExpireTime">
            <el-date-picker
                v-model="form.ticketExpireTime"
                type="datetime"
                placeholder="选择日期时间"
                :disabled-date="disabledDate"
                :shortcuts="shortcuts"
                value-format="x"
                :validate-event="true"/>
          </el-form-item>
          <el-form-item prop="userName" label="订购人姓名">
            <el-input  v-model="form.userName" placeholder="填写用户名"></el-input>
          </el-form-item>
          <el-form-item prop="emailAddress" label="订购人邮箱地址">
            <el-input v-model="form.emailAddress" placeholder="填写邮箱地址"></el-input>
          </el-form-item>
          <el-form-item prop="verify" label="验证码">
            <el-input v-model="form.verify" placeholder="验证码" style="width: 100px"/>&nbsp;
            <el-button :disabled="verifyDisabled" @click="getVerify" size="small" type="primary">获取验证码</el-button>
          </el-form-item>
        </el-form>
      </el-row>
    </div>
    <div v-else-if="active===1">
<!--      付款-->
      <h1>订单支付</h1>
      <el-divider/>
      <div>
        <el-table :data="ticket">
          <el-table-column label="入园时间">
            <template #default>
              {{timeFor}}
            </template>
          </el-table-column>
          <el-table-column label="门票名称" prop="scenicTicketName"></el-table-column>
          <el-table-column label="门票价格">
            <template #default="scope">
              {{scope.row.scenicTicketPrice}}元
            </template>
          </el-table-column>
          <el-table-column label="用户名">
            <template #default>
              {{form.userName}}
            </template>
          </el-table-column>
          <el-table-column label="邮箱地址">
            <template #default>
              {{form.emailAddress}}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作">
            <template #default>
              <el-button :loading="loading" v-if="!buyDisabled" type="primary" @click="buyTicket" >
                <i class="iconfont icon-goumai"/>
                &nbsp;购买</el-button>
              <el-tag v-if="buyDisabled">已购买</el-tag>
            </template>
          </el-table-column>

        </el-table>
      </div>
    </div>
    <div v-else>
      <el-row justify="center">
        <el-card shadow="never" style="width: 300px">
          <el-result icon="success" title="订购完成" subTitle="点击下方返回票务页">
            <template #extra>
              <el-button @click="backBuyTicket" type="primary" size="large">返回</el-button>
            </template>
          </el-result>
        </el-card>
        <el-divider/>
        <p>已购买的门票可前往<el-button @click="goMyTicket" type="text">我的门票</el-button>查看</p>
      </el-row>
    </div>
    <el-divider/>
    <el-button type="warning" v-if="active>0 && active<2"  @click="last" size="large">上一步</el-button>
    <el-button type="warning" v-if="active===0" @click="next" size="large">下一步</el-button>
  </div>
</template>

<script>
import {createOrder, getTicketById} from "@/api/ticket";
import {mapGetters} from "vuex";
import {getCaptcha, isExitUser} from "@/api/user";
import {dateFormat} from "@/utils/format";
export default {
  name: "index",
  props:['ticketId'],
  data(){
    return{
      loading:false,
      status1:'finish',
      status2:'wait',
      buyDisabled:false,
      timeFor:'',
      form:{
        emailAddress:'',
        userName:'',
        ticketExpireTime:'',
        verify:'',
      },
      verifyDisabled:false,
      captcha:'',
      ticketType:{'UnExpire':'可购买','Expire':'不可购买'},
      ticket:[],
      disabledDate(time) {
        return time.getTime()>=Date.now()+3600 * 1000 * 24*7 ||time.getTime()<Date.now()
      },
      shortcuts: [
        {
          text: '今天',
          value: new Date(),
        },
        {
          text: '明天',
          value: () => {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24)
            return date
          },
        },
        {
          text: '后天',
          value: () => {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 2)
            return date
          },
        },
        {
          text: '一周后',
          value: () => {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
            return date
          },
        },
      ],
      rules:{
        userName: [
          { required: true, message: '姓名不能为空', trigger:['blur','change'] },
        ],
        ticketExpireTime: [
          { required: true, message: '入园时间不能为空', trigger:['blur','change']},
          {
            validator: (rule, value, callback) => {
              const enterTime= new Date(value)
              const startTime=new Date(value)
              startTime.setHours(7)
              startTime.setMinutes(0)
              startTime.setSeconds(0)
              const endTime=new Date(value)
              endTime.setHours(19)
              endTime.setMinutes(0)
              endTime.setSeconds(0)
              const nowTime=new Date();
              if ( enterTime<startTime || enterTime>endTime){
                callback(new Error('请选择7:00-19:00时间段内的时间'))
              }else if(enterTime<nowTime) {
                callback(new Error('选择的时间已经过去'))
              }
                else {
                callback()
              }
            },trigger:['change','blur']
          }
        ],
        emailAddress: [
          { required: true, message: '邮箱地址不能为空', trigger:['blur','change'] },
        ],
        verify: [
          {required: true, message:'验证码不能为空', trigger: ['change','blur']},
          {validator: (rule, value, callback) => {
              if (this.captcha===''){
                callback(new Error('您还未获取验证码'))
              }
              else if (value!==this.captcha) {
                callback(new Error('验证码不正确'))
              } else {
                callback()
              }
            }, trigger: ['change','blur']}
        ]
      },
      active:0,
    }
  },
  computed:{
    ...mapGetters(['username','email'])
  },
  mounted() {
    this.getTicket()
    this.form.userName=this.username
    this.form.emailAddress=this.email
  },
  watch:{
    'form.ticketExpireTime':{
      handler(newVal){
        this.timeFor=dateFormat(newVal,false)
      },
      deep:true
    }
  },
  methods:{
    buyTicket(){
      this.loading=true
      const id=sessionStorage.getItem("userId")
      const form={
        userId:id,
        ticketId:this.ticket[0].scenicTicketId,
        ticketName:this.ticket[0].scenicTicketName,
        ticketExpireTime:this.form.ticketExpireTime,
        ticketPrice:this.ticket[0].scenicTicketPrice
      }
      createOrder(form)
          .then(()=>{
            this.status2='success'
            this.buyDisabled=true
            this.loading=false
            this.active+=1
          })
          .catch(() =>{
            this.loading=false
            this.status2='error'
          })
    },
    //获取验证码
    getVerify(){
      if (this.form.emailAddress===''){
        this.$message({
          type:'warning',
          message:'邮箱地址为空'
        })
        return
      }
      const b = /^\w+@[\da-z\\.-]+\.([a-z]{2,6}|[\u2E80-\u9FFF]{2,3})$/.test(this.form.emailAddress);
      //验证邮箱格式
      if (!b){
        this.$message({
          type:'warning',
          message:'邮箱格式错误'
        })
        return
      }
      getCaptcha(this.form.emailAddress).then(res =>{
        this.verifyDisabled=true;
        this.captcha=res.data.verify;
      }).catch(error =>{
        console.log(error)
      })
      setTimeout(()=>{
        this.verifyDisabled=false;
      },5000)
    },
    //根据id获取门票信息
    getTicket(){
      getTicketById(this.ticketId).then(response=>{
        this.ticket.push(response.data.ticket)
      })
    },
    //激活上一个选项
    last(){
      if(this.active===1) {
        this.status2 = 'wait'
        this.status1 = 'finish'
      }
        this.active-=1
    },
    //表单验证
    next() {
      this.$refs.orderForm.validate((valid) =>{
        if (valid){
          const n=sessionStorage.getItem("name")
          const e=sessionStorage.getItem("email")
          if (n===this.form.userName && e===this.form.emailAddress){
            this.status2='finish'
            this.status1='success'
            this.captcha=''
            this.buyDisabled=false
            this.active+=1
          }else {
            isExitUser(this.form.userName,this.form.emailAddress).then(response=>{
              if (response.data.userId!==null){
                //当用户通过该验证就保存起来，当通过上一步（last按钮）来重新进入时获取本地值，来判断是否要重新询问后台
                sessionStorage.setItem("name",this.form.userName)
                sessionStorage.setItem("email",this.form.emailAddress)
                sessionStorage.setItem("userId",response.data.userId)
                this.status1='success'
                this.status2='finish'
                this.captcha=''
                this.buyDisabled=false
                this.active+=1
              }
            }).catch(()=>{
              this.status1='error'
            })
          }
        }
      })
    },
    //返回票务页
    backBuyTicket(){
      this.$router.replace('/smart/getTicket')
    },
    //前往个人中心，我的门票
    goMyTicket(){
      this.$router.replace('/profile/user/userTicket')
    }
  }
}
</script>

<style scoped>
/deep/ .el-input__inner{

}
/deep/ .el-input{
}
</style>
